package com.inspinia.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * CookieUtils : 针对Http Cookie的工具类
 *
 * @author StarZou
 * @since 2014-09-28 22:31
 */
public class CookieUtils {

    protected static Logger logger = LoggerFactory.getLogger(CookieUtils.class);

    /**
     * 设置 Cookie, 过期时间为30分钟
     *
     * @param name  名称
     * @param value 值
     */
    public static Cookie setCookie(HttpServletResponse response, String name, String value, String path) {
        return addCookie(response, name, value, path, 60 * 30);
    }


    /**
     * 设置 Cookie, 过期时间为30分钟
     *
     * @param name  名称
     * @param value 值
     */
    public static Cookie setCookie(HttpServletResponse response, String name, String value, String path,int maxAge) {
        return addCookie(response, name, value, path, maxAge);
    }

    /**
     * 设置 Cookie, 过期时间自定义
     *
     * @param name   名称
     * @param value  值
     * @param maxAge 过期时间, 单位秒
     */
    public static Cookie addCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
        Cookie cookie = null;
        try {
            cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
            cookie.setMaxAge(maxAge);
            if (null != path) {
                cookie.setPath(path);
            }
            cookie.setSecure(true);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return cookie;
    }


    /**
     * 设置 Cookies, 过期时间自定义
     *
     * @param response 响应对象
     * @param values   值
     * @param path     路径
     * @param maxAge   过期时间, 单位秒
     * @return Cookies
     */
    public static ArrayList<Cookie> addCookies(HttpServletResponse response, Map<String, String> values, String path, int maxAge) {
        Set<Map.Entry<String, String>> entries = values.entrySet();
        ArrayList<Cookie> cookies = new ArrayList<Cookie>();
        try {
            for (Map.Entry<String, String> entry : entries) {
                Cookie cookie = new Cookie(entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8"));
                cookie.setMaxAge(maxAge);
                if (null != path) {
                    cookie.setPath(path);
                }
                response.addCookie(cookie);
                cookies.add(cookie);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return cookies;
    }


    /**
     * 获得指定Cookie的值
     *
     * @param name 名称
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, String name) {
        return getCookie(request, null, name, false);
    }

    /**
     * 获得指定Cookie的值，并删除。
     *
     * @param name 名称
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        return getCookie(request, response, name, true);
    }

    /**
     * 获得指定Cookie的值
     *
     * @param request   请求对象
     * @param response  响应对象
     * @param name      名字
     * @param isRemoved 是否移除
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemoved) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    try {
                        value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if (isRemoved) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                    return value;
                }
            }
        }
        return value;
    }

    public static void authJSESSIONID(HttpServletRequest request, String value) {
        request.getSession().invalidate();
        request.getSession().setAttribute("INSSSO-" + value, true);
    }

    public static Cookie findCookieByName(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        } else {
            for(int i = 0; i < cookies.length; ++i) {
                if (cookies[i].getName().equals(cookieName)) {
                    return cookies[i];
                }
            }

            return null;
        }
    }

    public static void clearCookieByName(HttpServletResponse response, String cookieName) {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static void clearAllCookie(HttpServletRequest request, HttpServletResponse response, String domain, String path) {
        Cookie[] cookies = request.getCookies();

        for(int i = 0; i < cookies.length; ++i) {
            clearCookie(response, cookies[i].getName(), domain, path);
        }

        logger.info("clearAllCookie in  domain " + domain);
    }

    public static boolean clearCookieByName(HttpServletRequest request, HttpServletResponse response, String cookieName, String domain, String path) {
        boolean result = false;
        Cookie ck = findCookieByName(request, cookieName);
        if (ck != null) {
            result = clearCookie(response, cookieName, domain, path);
        }

        return result;
    }

    private static boolean clearCookie(HttpServletResponse response, String cookieName, String domain, String path) {
        boolean result = false;

        try {
            Cookie cookie = new Cookie(cookieName, "");
            cookie.setMaxAge(0);
            cookie.setDomain(domain);
            cookie.setPath(path);
            response.addCookie(cookie);
            logger.info("clear cookie " + cookieName);
            result = true;
        } catch (Exception var6) {
            logger.info("clear cookie " + cookieName + " is exception!\n" + var6.toString());
        }

        return result;
    }

    public static void addCookie(HttpServletResponse response, String domain, String path, String name, String value, int maxAge, boolean httpOnly, boolean secured) {
        Cookie cookie = new Cookie(name, value);
        if (domain != null && !"".equals(domain)) {
            cookie.setDomain(domain);
        }

        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        if (secured) {
            cookie.setSecure(secured);
        }

        if (httpOnly) {
            addHttpOnlyCookie(response, cookie);
        } else {
            response.addCookie(cookie);
        }

    }

    public static void addHttpOnlyCookie(HttpServletResponse response, Cookie cookie) {
        if (cookie != null) {
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            int maxAge = cookie.getMaxAge();
            String path = cookie.getPath();
            String domain = cookie.getDomain();
            boolean isSecure = cookie.getSecure();
            StringBuffer sf = new StringBuffer();
            sf.append(cookieName + "=" + cookieValue + ";");
            if (maxAge >= 0) {
                sf.append("Max-Age=" + cookie.getMaxAge() + ";");
            }

            if (domain != null) {
                sf.append("domain=" + domain + ";");
            }

            if (path != null) {
                sf.append("path=" + path + ";");
            }

            if (isSecure) {
                sf.append("secure;HTTPOnly;");
            } else {
                sf.append("HTTPOnly;");
            }

            response.addHeader("Set-Cookie", sf.toString());
        }
    }
}
